package top.codedance.iotp.client.net.handler;

import cd.io.netty.buffer.ByteBuf;
import cd.io.netty.buffer.Unpooled;
import cd.io.netty.channel.ChannelFutureListener;
import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.handler.codec.http.*;
import cd.io.netty.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.net.AbstractHttpServer;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class HttpMsgHandlerImpl implements HttpMsgHandler {

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest request = (FullHttpRequest) msg;
        ByteBuf body = request.content();
        byte[] bodyArr = new byte[body.readableBytes()];
        body.readBytes(bodyArr);
        String uri = request.uri();
        Set<Map.Entry<String, Controller>> entries = AbstractHttpServer.httpRoutes.entrySet();
        String content = "";
        boolean isFindHandler = false;
        for(Map.Entry<String, Controller> entity : entries){
            if(uri.matches(entity.getKey())){
                content = entity.getValue().doHandler(bodyArr);
                isFindHandler = true;
                break;
            }
        }
        if(!isFindHandler){
            JSONObject result = new JSONObject();
            result.put("status", 404);
            result.put("message", "Not find page.");
            content = result.toJSONString();
        }
        sendResponse(ctx, content.getBytes(StandardCharsets.UTF_8));
    }

    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    }

    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    private void sendResponse(ChannelHandlerContext ctx, byte[] content){
        String contentString = new String(content, StandardCharsets.UTF_8);
        ByteBuf byteBuf = Unpooled.copiedBuffer(contentString, CharsetUtil.UTF_8);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, byteBuf);
        response.setStatus(HttpResponseStatus.OK);
        HttpHeaders headers = response.headers();
        headers.set("Content-Type", "application/json; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
